package com.yitong.equipment.ui.viewmodel

import android.app.Application
import androidx.annotation.NonNull
import androidx.lifecycle.*
import com.blankj.utilcode.util.LogUtils
import com.yitong.equipment.App
import com.yitong.equipment.base.BaseViewModel
import com.yitong.equipment.database.YtDataBase
import com.yitong.equipment.database.entity.User
import com.yitong.equipment.entity.base.BaseReq
import com.yitong.equipment.entity.base.BaseRes
import com.yitong.equipment.entity.res.HomeDataRes
import com.yitong.equipment.network.ApiCallback
import com.yitong.equipment.network.SubscriberCallBack
import io.reactivex.disposables.Disposable
import kotlinx.coroutines.*

class HomeViewModel(@NonNull application: Application) : BaseViewModel(application) {

    val homeData by lazy { MutableLiveData<BaseRes<HomeDataRes>>() }
    val listUsers by lazy { MutableLiveData<List<User>>() }

    /**
     * 首页数据接口
     */
    fun getData() {
        var req = BaseReq()
        apiService.getHomeData(req).execute(SubscriberCallBack(object : ApiCallback<BaseRes<HomeDataRes>> {

            override fun onSuccess(model: BaseRes<HomeDataRes>) {
                homeData.value = model
            }

            override fun onFailure(code: Int, msg: String?) {
            }

            override fun onSubscribe(d: Disposable?) {
                addDisposable(d)
            }

            override fun onCompleted() {

            }

        }))

    }

    fun getData1() {
        viewModelScope.launch {
            getNetData(apiService.getHomeData1(BaseReq()),
                onSuccess = {
                var result = it.result
                LogUtils.dTag("result1111", result.toString())
                homeData.value = it
                },
                onFailed = {
                LogUtils.dTag("result1111", "onFailed")
                },
                onComplete ={
                LogUtils.dTag("result1111", "onComplete")
                }
            )
        }


    }

    fun saveUser(users: List<User>) {
        YtDataBase.getInstance(App.instance).userDao().addUsers(users).subscribeDbWithoutCallBack({
            YtDataBase.getInstance(App.instance).userDao().getUsers().subscribeDbWithCallBack({
//                        onSuccess(it)
            }, {
//                        onFailed(it)
            })
        }, {
//            onFailed(it)
        })


    }


    fun getUserByNamePhone(name: String, phone: String) {

        YtDataBase.getInstance(App.instance).userDao().getUserByNamePhone(name, phone).subscribeDbWithCallBack({
//                onSuccess(it)
        }, {
//                onFailed(it)
        })
    }

    fun getUser1() {
        launch(false) {
            var users1 = YtDataBase.getInstance(App.instance).userDao().getUsers1()
            launch(true) {
                listUsers.value = users1
            }
        }
    }



}